package com.myworkspace.standard.common.utils;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

public class HttpClientUtil {

    public String doPost(String url, Map<String, String> params) throws IOException {
        HttpEntity entity = doPost(url, null, params);
        return EntityUtils.toString(entity);
    }

    /**
     * 默认post 请求
     *
     * @param url     请求路径
     * @param headers 请求头
     * @param params  请求参数
     * @return
     */
    public HttpEntity doPost(String url, Map<String, String> headers, Map<String, String> params) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        ReentrantLock lock = new ReentrantLock(false);
        lock.lock();
        lock.unlock();
        try {
            AtomicInteger atomicInteger = new AtomicInteger(2);
            atomicInteger.incrementAndGet();
            // httpClient 实例初始化 默认模式
            httpClient = HttpClients.createDefault();
            BasicClientCookie cookie = new  BasicClientCookie("name", "value");
            RequestConfig requestConfig = RequestConfig.custom()
                    // 连接超时
                    .setConnectTimeout(1000)
                    // cookie策略
                    .setCookieSpec(CookieSpecs.STANDARD)
                    // 连接
                    .setConnectionRequestTimeout(1000).build();
            BasicCookieStore cookieStore = new BasicCookieStore();
            cookieStore.addCookie(cookie);

            HttpClients.custom()
                    // 配置
                    .setDefaultRequestConfig(requestConfig)
                    // cookie
                    .setDefaultCookieStore(cookieStore)
                    // ssl链接
//                    .setSSLSocketFactory()
                    // 代理设置
//                    .setProxy()
                    .build();
            // 请求方法初始化 post
            HttpPost post = new HttpPost(url);
            // 请求头参数
            if (headers != null && headers.size() > 0) {
                Iterator<String> iterator = headers.keySet().iterator();
                while (iterator.hasNext()) {
                    String name = iterator.next();
                    String value = headers.get(name);
                    post.addHeader(new BasicHeader(name, value));
                }
            }
            // post 请求参数
            if (params != null && params.size() > 0) {
                List<NameValuePair> list = new ArrayList<NameValuePair>();
                Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, String> next = iterator.next();
                    String name = next.getKey();
                    String value = next.getValue();
                    list.add(new BasicNameValuePair(name, value));
                }
                if (list.size() > 0) {
                    post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
                }
            }
            // 执行post请求 获得响应对象
            response = httpClient.execute(post);
            entity = response.getEntity();
            // 状态吗
            System.out.println(response.getStatusLine().getStatusCode());
            // http 协议版本
            System.out.println(response.getStatusLine().getProtocolVersion());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return entity;
    }
}
